import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xterm/xterm.dart' as xterm;
import 'controller.dart';

/// 终端页面（支持双指缩放字体大小）

class TerminalPage extends GetView<TerminalController> {
  const TerminalPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () => Get.back(),
        ),
        title: Obx(() => Text(controller.server.value?.name ?? '终端')),
        actions: [
          // 字体大小显示 & 重置
          Obx(() => PopupMenuButton<String>(
            icon: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(Icons.text_fields, size: 20),
                const SizedBox(width: 4),
                Text(
                  '${controller.fontSize.value.toInt()}',
                  style: const TextStyle(fontSize: 12),
                ),
              ],
            ),
            tooltip: '字体大小',
            onSelected: (value) {
              switch (value) {
                case 'increase':
                  controller.increaseFontSize();
                  break;
                case 'decrease':
                  controller.decreaseFontSize();
                  break;
                case 'reset':
                  controller.resetFontSize();
                  break;
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'increase',
                child: Row(
                  children: [
                    Icon(Icons.add),
                    SizedBox(width: 8),
                    Text('增大字体'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'decrease',
                child: Row(
                  children: [
                    Icon(Icons.remove),
                    SizedBox(width: 8),
                    Text('减小字体'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'reset',
                child: Row(
                  children: [
                    Icon(Icons.refresh),
                    SizedBox(width: 8),
                    Text('重置字体'),
                  ],
                ),
              ),
            ],
          )),
          // 清屏按钮
          IconButton(
            icon: const Icon(Icons.cleaning_services),
            onPressed: controller.clearScreen,
            tooltip: '清屏',
          ),
          // 断开连接按钮
          Obx(() {
            if (controller.isConnected.value) {
              return IconButton(
                icon: const Icon(Icons.power_off),
                onPressed: () => _showDisconnectDialog(context),
                tooltip: '断开连接',
              );
            }
            return const SizedBox.shrink();
          }),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value && !controller.isConnected.value) {
          return const Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text('正在连接终端...'),
              ],
            ),
          );
        }

        return Column(
          children: [
            // 终端视图（支持手势缩放）
            Expanded(
              child: _TerminalGestureWrapper(
                controller: controller,
              ),
            ),
            
            // 虚拟键盘（移动端）
            if (MediaQuery.of(context).size.width < 600) ...[
              _buildVirtualKeyboard(),
            ],
          ],
        );
      }),
    );
  }

  /// 构建虚拟键盘
  Widget _buildVirtualKeyboard() {
    return Container(
      height: 50,
      color: Colors.grey[900],
      child: ListView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        children: [
          _buildKeyButton('Esc', '\x1b', Colors.red[700]),
          _buildKeyButton('Tab', '\t', Colors.blue[700]),
          _buildKeyButton('Ctrl', '', Colors.purple[700], isModifier: true),
          const SizedBox(width: 16),
          _buildKeyButton('↑', '\x1b[A', Colors.grey[700]),
          _buildKeyButton('↓', '\x1b[B', Colors.grey[700]),
          _buildKeyButton('←', '\x1b[D', Colors.grey[700]),
          _buildKeyButton('→', '\x1b[C', Colors.grey[700]),
          const SizedBox(width: 16),
          _buildKeyButton('Home', '\x1b[H', Colors.grey[700]),
          _buildKeyButton('End', '\x1b[F', Colors.grey[700]),
          _buildKeyButton('PgUp', '\x1b[5~', Colors.grey[700]),
          _buildKeyButton('PgDn', '\x1b[6~', Colors.grey[700]),
          const SizedBox(width: 16),
          _buildKeyButton('F1', '\x1bOP', Colors.grey[700]),
          _buildKeyButton('F2', '\x1bOQ', Colors.grey[700]),
          _buildKeyButton('F3', '\x1bOR', Colors.grey[700]),
          _buildKeyButton('F4', '\x1bOS', Colors.grey[700]),
          _buildKeyButton('F5', '\x1b[15~', Colors.grey[700]),
          _buildKeyButton('F6', '\x1b[17~', Colors.grey[700]),
          _buildKeyButton('F7', '\x1b[18~', Colors.grey[700]),
          _buildKeyButton('F8', '\x1b[19~', Colors.grey[700]),
          _buildKeyButton('F9', '\x1b[20~', Colors.grey[700]),
          _buildKeyButton('F10', '\x1b[21~', Colors.grey[700]),
        ],
      ),
    );
  }

  /// 构建按键按钮
  Widget _buildKeyButton(
    String label,
    String sequence,
    Color? backgroundColor, {
    bool isModifier = false,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 2),
      child: ElevatedButton(
        onPressed: isModifier
            ? null  // 修饰键暂不实现（需要组合键逻辑）
            : () => controller.sendKey(sequence),
        style: ElevatedButton.styleFrom(
          backgroundColor: backgroundColor,
          foregroundColor: Colors.white,
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          minimumSize: const Size(0, 36),
          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
        ),
        child: Text(
          label,
          style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600),
        ),
      ),
    );
  }

  /// 显示断开连接确认对话框
  void _showDisconnectDialog(BuildContext context) {
    Get.dialog(
      AlertDialog(
        title: const Text('断开连接'),
        content: const Text('确定要断开终端连接吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.disconnect();
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('断开'),
          ),
        ],
      ),
    );
  }
}

/// 终端手势包装器（支持双指缩放调整字体大小）
class _TerminalGestureWrapper extends StatefulWidget {
  final TerminalController controller;

  const _TerminalGestureWrapper({
    required this.controller,
  });

  @override
  State<_TerminalGestureWrapper> createState() => _TerminalGestureWrapperState();
}

class _TerminalGestureWrapperState extends State<_TerminalGestureWrapper> {
  double? _initialFontSize;  // 缩放开始时的字体大小
  double _currentScale = 1.0;  // 当前缩放比例

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final fontSize = widget.controller.fontSize.value;
      
      return GestureDetector(
        // 缩放开始
        onScaleStart: (details) {
          _initialFontSize = fontSize;
          _currentScale = 1.0;
        },
        // 缩放中
        onScaleUpdate: (details) {
          if (_initialFontSize != null) {
            // 根据缩放比例计算新的字体大小
            final newFontSize = _initialFontSize! * details.scale;
            widget.controller.setFontSize(newFontSize);
            _currentScale = details.scale;
          }
        },
        // 缩放结束
        onScaleEnd: (details) {
          _initialFontSize = null;
          _currentScale = 1.0;
        },
        child: Container(
          color: Colors.black,
          child: xterm.TerminalView(
            widget.controller.terminal,
            controller: widget.controller.terminalController,
            autofocus: true,
            backgroundOpacity: 1.0,
            // 动态应用字体大小
            textStyle: xterm.TerminalStyle.fromTextStyle(
              TextStyle(fontSize: fontSize),
            ),
          ),
        ),
      );
    });
  }
}

